//
//  RainbowView.m
//  UI03_Homework_彩虹灯
//
//  Created by Scott on 16/5/6.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "RainbowView.h"

@interface RainbowView ()

// 存放颜色对象数组.
@property (nonatomic, retain) NSMutableArray *arrOfColor;

@property (nonatomic, retain) NSTimer *timer;

@end


@implementation RainbowView

- (void)dealloc {
    
    [_arrOfColor release];
    [_timer release];
    [super dealloc];
}


#pragma mark - Creating and Init
- (instancetype)initWithFrame:(CGRect)frame numberOfView:(NSInteger)number duration:(NSTimeInterval)duration {
    
    self = [super initWithFrame:frame];
    if (self) {
        
        // 初始化数组.
        [self setColors:number];
        
        // 创建子视图.
        [self createSubViewsWithFrame:frame numberOfView:number];
        
        // 计时器
        self.timer = [NSTimer scheduledTimerWithTimeInterval:duration target:self selector:@selector(changeColor:) userInfo:@{@"number":[NSNumber numberWithInteger:number]} repeats:YES];
        
        
    }
    return self;
}

#pragma mark -

- (void)changeColor:(NSTimer *)timer {
   NSInteger number = [[timer.userInfo objectForKey:@"number"] integerValue];
    
    for (int i = 0; i < number; i++) {
        [self viewWithTag:i + 1].backgroundColor = [self viewWithTag:i + 1 + 1].backgroundColor;
        
        if (i == number - 1) {
            [self viewWithTag:i + 1].backgroundColor = [self viewWithTag:1].backgroundColor;
        }
    }
}



- (void)setColors:(NSInteger)number {
    
    self.arrOfColor = [NSMutableArray arrayWithCapacity:number];
    
    for (int i = 0; i < number; i++) {
        
        UIColor *color = [UIColor colorWithRed:arc4random() % 256 / 255.f green:arc4random() % 256 / 255.f blue:arc4random() % 256 / 255.f alpha:1];
        [self.arrOfColor addObject:color];
    }
}

- (void)createSubViewsWithFrame:(CGRect)frame numberOfView:(NSInteger)number {
    
    for (int i = 0 ; i < number; i++) {
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width / number * (number - i), frame.size.height / number * (number - i))];
        
        view.center = self.center;

        view.backgroundColor = self.arrOfColor[i];
        
        view.tag = i + 1;
        
        
        [self addSubview:view];
        [view release];
    }
}





@end
